#导包
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, auc, confusion_matrix
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA

# 导入数据集
df = pd.read_csv('E:/PROJECT_Dynasty2023/project_-dynasty2023/Project_MachineLearning/titanic_dataset.csv')


#填补缺失值
####################################################################################
y_train1=df['Survived']
X_train=df.drop('Survived',axis=1)



# 将数据集中的NaN数据使用中值填充。
Xtrain1=X_train.copy()
#np.nanmedian沿指定轴计算中位数，而忽略NaN。
Xtrain1['Age'].replace(np.nan, np.nanmedian(Xtrain1['Age']),inplace=True)

#同时考虑性别和仓位
age_Pclass=X_train.groupby(['Pclass','Sex']).Age.median()
X_train.set_index(['Pclass','Sex'],inplace=True)
X_train.Age.fillna(age_Pclass,inplace=True)
X_train.reset_index(inplace=True)

# Cabin 的缺失值太多，从 Dataframe 中移除后，也不会影响预测的
X_train.drop("Cabin", axis=1, inplace=True)
# 我们来看下乘客都在哪些站登船的
# S 表示：Southampton，英国南安普敦
# C 表示：Cherbourg-Octeville，法国瑟堡-奥克特维尔
# Q 表示：Queenstown，爱尔兰昆士敦
X_train.Embarked.value_counts()
X_train['Embarked'].replace(np.nan, 'S', inplace=True)
# 查询从 英国南安普敦 上船，级别是3的船票价格
pclass3_fares = X_train.query('Pclass == 3 & Embarked == "S"')['Fare']
# 先将空值填充为0
pclass3_fares = pclass3_fares.replace(np.nan, 0)
# 然后取中值
median_fare = np.median(pclass3_fares)
# 最后更新中值到缺失值的那处
X_train.loc[X_train['PassengerId'] == 1044, 'Fare'] = median_fare
X_train['Sex'].replace(['male', 'female'], [1,0], inplace=True)
X_train.isnull().sum()
#转化为计算机可以识别的
X_train['Embarked'].replace(['S', 'C','Q'], [1,2,3], inplace=True)
#数据集中name和ID重合了，删掉name
data=X_train.drop('Name',axis=1)
#也是重合了删掉船票编号
data.drop('Ticket',axis=1,inplace=True)
data.drop('PassengerId',axis=1,inplace=True)
####################################################################################
X = data
y = y_train1

# 3.数据预处理（填补缺失值代码需要自行填写）
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
mms=preprocessing.MinMaxScaler()
X_train=mms.fit_transform(X_train)
X_test = mms.transform(X_test)
pca = PCA(n_components=2)
X_train=pca.fit_transform(X_train)
X_test=pca.transform(X_test)

# 4.计算ROC曲线的X轴坐标和Y轴坐标，混淆矩阵
#计算TPR，FPR,AUC
svm = SVC(probability=True)
svm.fit(X_train, y_train)
y_score_svm = svm.predict_proba(X_test)[:, 1]
fpr_svm, tpr_svm, _ = roc_curve(y_test, y_score_svm)
roc_auc_svm = auc(fpr_svm, tpr_svm)

lr = LogisticRegression(max_iter=1000)
lr.fit(X_train, y_train)
y_score_lr = lr.predict_proba(X_test)[:,1]
fpr_lr,tpr_lr, _= roc_curve(y_test,y_score_lr)
roc_auc_lr =auc(fpr_lr,tpr_lr)

#混淆矩阵
y_pred_svm = svm.predict(X_test)
cm = confusion_matrix(y_test,y_pred_svm)

plt.figure()
plt.plot(fpr_svm, tpr_svm, color='darkorange', lw=2, label='SVM (AUC = {:.2f})'.format(roc_auc_svm))
plt.plot(fpr_lr, tpr_lr, color='blue', lw=2, label='LR (AUC = {:.2f})'.format(roc_auc_lr))
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right")
plt.show()
